package com.snake.springboot.authority.service.listener;

import com.snake.springboot.authority.api.model.AccountInfoModel;
import com.snake.springboot.authority.api.model.AuthInterfaceModel;
import com.snake.springboot.authority.api.model.AuthRuleModel;
import com.snake.springboot.authority.api.service.AuthInterfaceService;
import com.snake.springboot.authority.service.config.AuthProperties;
import com.snake.springboot.authority.service.event.AccountIdentifyEvent;
import com.snake.springboot.authority.service.event.LoadAuthRuleEvent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snake.common.result.ResponseResult;
import org.snake.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类 {@code AuthorityListener}  <br> .
 * <p>权限监听器</p>
 * 创建时间：2024/6/3 16:36
 *
 * @author Yzhui
 * @see
 */
@Component
public class SystemAuthorityListener {

    private static final Logger logger = LoggerFactory.getLogger(SystemAuthorityListener.class);

    @Autowired
    private AuthInterfaceService authInterfaceService;
    @Resource
    private AuthProperties authProperties;
    @Resource
    private RestTemplate restTemplate;

    @EventListener(LoadAuthRuleEvent.class)
    public void onLoadAuthRule(LoadAuthRuleEvent event) {
        logger.info("----------------推送加载权限规则事件----------------------");
        AuthInterfaceModel params = new AuthInterfaceModel();
        params.setWhitelistFlag(event.getPermsFlag());
        List<AuthRuleModel> authRuleList = null;
        try {
            authRuleList = authInterfaceService.queryAuthRuleList(params);
        }catch (Exception e) {
            logger.error("权限加载失败!原因：{}", e.getMessage());
        }
        event.setAuthRules(authRuleList);
    }

    @EventListener
    public void onAccountIdentify(AccountIdentifyEvent event) {
        Map<String,Object> map = new HashMap<>(2);
        map.put("type", event.getType());
        map.put("accountId", event.getAccountId());
        String chooseUrl = authProperties.chooseUrl(event.getType());
        if (StringUtils.isEmpty(chooseUrl)) {
            return;
        }
        ResponseResult<Object> body = restTemplate.postForEntity(chooseUrl, map, ResponseResult.class).getBody();

        Object data = body.getData();
        if (data!=null){
            AccountInfoModel infoModel = JsonUtils.fromJson(JsonUtils.toJson(data), AccountInfoModel.class);
            event.setResult(infoModel);
        }
    }

}
